/*
 * @Description: 
 * @Author: chenjiaxin
 * @Date: 2024-11-21 15:03:55
 * @LastEditTime: 2024-11-22 16:15:09
 */
import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";

// 游戏控制器
class GameControl {
  public snake: Snake;
  public food: Food;
  public scorePanel: ScorePanel;
  public direction: string = "";
  public isLive: boolean = true; // 记录游戏是否结束
  constructor() {
    this.snake = new Snake();
    this.food = new Food();
    this.scorePanel = new ScorePanel();

    // 游戏开始
    this.init();
  }

  init() {
    // 绑定键盘按下的事件
    document.addEventListener("keydown", this.keydownHandler.bind(this));

    this.run();
  }

  /*
  chrome:
  ArrowUp
  ArrowDown
  ArrowLeft
  ArrowRight

  ie:
  Up
  Down
  Left
  Right
  */
  keydownHandler(event: KeyboardEvent) {
    console.log(this);
    this.direction = event.key;
  }

  checkEat(X: number, Y: number) {
    if(X === this.food.X && Y === this.food.Y) {
      this.food.change()
      this.scorePanel.addScore()
      this.snake.addBody()
    }
  }

  run() {
    let X = this.snake.X;
    let Y = this.snake.Y;
    switch (this.direction) {
      case "ArrowUp":
      case "Up":
        Y -= 10;
        break;
      case "ArrowDown":
      case "Down":
        Y += 10;
        break;
      case "ArrowLeft":
      case "Left":
        X -= 10;
        break;
      case "ArrowRight":
      case "Right":
        X += 10;
        break;
    }

    // 检查是否吃到食物
    this.checkEat(X,Y)

    try{
      this.snake.X = X
      this.snake.Y = Y
    }catch(e) {
      if (e instanceof Error) {
        alert(e.message)
        this.isLive = false
      }
    }

    this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
  }
}

export default GameControl;
